package com.jy.api.timer;

import com.jy.api.aspect.RedisLocker;
import com.jy.api.dao.EmployeeDao;
import com.jy.api.dao.WorkShiftDao;
import com.jy.api.domain.Employee;
import com.jy.api.domain.WorkShift;
import com.jy.api.service.TableService;
import com.jy.api.service.WechatTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class ScheduledTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WorkShiftDao workShiftDao;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    WechatTemplateService wechatTemplateService;
    @Autowired
    private TableService tableService;

    @Scheduled(cron = "*/5 * * * * ?") //每分钟执行一次
    public void workshiftTimer() {
        redisTemplate.execute((RedisCallback) redisConnection -> {
            byte[] bytes = redisConnection.sPop("workshifts".getBytes());
            if (null != bytes) {
                String ids = new String(bytes);
                log.info("send template message to :" + ids);
                String[] split = ids.split("#");
                String workshiftId = split[0];
                Employee employee = null;
                if (split.length > 1) {
                    employee = employeeDao.findOne(split[1]);
                }
                if (null != workshiftId && workshiftId.length() > 8) {
                    WorkShift workShift = workShiftDao.findOne(workshiftId);
                    if (null != workShift) {
                        wechatTemplateService.sendWorkshift(workShift, employee);
                    }
                }
            }
            return true;
        });
    }

    @RedisLocker(lockKey = "SchedulerTask.tableMove", holdTime = 10)
    @Scheduled(cron = "0 1/2 6 * * ?")
    public void tableMove() {
        final List<String> result = tableService.backup();
        log.info(Arrays.toString(result.toArray()));
    }
}
